#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git仓库迁移工具命令行界面
提供交互式配置和迁移功能
"""

import os
import sys
import json
import argparse
from git_migrator import GitMigrator


def create_config_interactive():
    """交互式创建配置文件"""
    print("=== Git仓库迁移工具配置向导 ===\n")
    
    config = {}
    
    # 源仓库配置
    print("【源仓库配置】")
    config['source_repo'] = input("请输入源Git仓库URL (例如: https://github.com/username): ").strip()
    config['source_username'] = input("请输入源仓库用户名 (可选): ").strip()
    config['source_password'] = input("请输入源仓库密码 (可选): ").strip()
    
    # 目标GitLab配置
    print("\n【目标GitLab配置】")
    config['target_gitlab_url'] = input("请输入目标GitLab仓库URL (例如: https://gitlab.com): ").strip()
    config['target_access_token'] = input("请输入GitLab访问令牌: ").strip()
    config['target_project_path'] = input("请输入目标项目路径 (例如: group/subgroup): ").strip()
    
    # 本地配置
    print("\n【本地配置】")
    config['local_temp_path'] = input("请输入本地临时存储路径 (默认: ./temp): ").strip()
    if not config['local_temp_path']:
        config['local_temp_path'] = "./temp"
    
    # 源项目路径配置
    print("\n【源项目路径配置】")
    print("请输入需要迁移的项目路径，每行一个，输入空行结束:")
    project_paths = []
    while True:
        path = input("项目路径: ").strip()
        if not path:
            break
        project_paths.append(path)
    
    if not project_paths:
        print("错误：至少需要指定一个项目路径")
        return None
        
    config['source_project_paths'] = project_paths
    
    return config


def save_config(config, filename="config.json"):
    """保存配置文件"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
        print(f"\n配置文件已保存到: {filename}")
        return True
    except Exception as e:
        print(f"保存配置文件失败: {e}")
        return False


def load_config(filename="config.json"):
    """加载配置文件"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"配置文件 {filename} 不存在")
        return None
    except json.JSONDecodeError:
        print(f"配置文件 {filename} 格式错误")
        return None


def show_config(config):
    """显示配置信息"""
    print("\n=== 当前配置信息 ===")
    print(f"源仓库URL: {config.get('source_repo', '未设置')}")
    print(f"源仓库用户名: {config.get('source_username', '未设置')}")
    print(f"目标GitLab URL: {config.get('target_gitlab_url', '未设置')}")
    print(f"目标项目路径: {config.get('target_project_path', '未设置')}")
    print(f"本地临时路径: {config.get('local_temp_path', '未设置')}")
    print(f"源项目路径: {', '.join(config.get('source_project_paths', []))}")


def edit_config():
    """编辑配置文件"""
    config = load_config()
    if not config:
        return
        
    print("=== 编辑配置 ===")
    show_config(config)
    
    while True:
        print("\n选择要编辑的配置项:")
        print("1. 源仓库配置")
        print("2. 目标GitLab配置")
        print("3. 本地配置")
        print("4. 源项目路径")
        print("0. 返回")
        
        choice = input("请选择 (0-4): ").strip()
        
        if choice == "0":
            break
        elif choice == "1":
            config['source_repo'] = input(f"源仓库URL (当前: {config.get('source_repo', '未设置')}): ").strip()
            config['source_username'] = input(f"用户名 (当前: {config.get('source_username', '未设置')}): ").strip()
            config['source_password'] = input(f"密码 (当前: {config.get('source_password', '未设置')}): ").strip()
        elif choice == "2":
            config['target_gitlab_url'] = input(f"GitLab URL (当前: {config.get('target_gitlab_url', '未设置')}): ").strip()
            config['target_access_token'] = input(f"访问令牌 (当前: {config.get('target_access_token', '未设置')}): ").strip()
            config['target_project_path'] = input(f"项目路径 (当前: {config.get('target_project_path', '未设置')}): ").strip()
        elif choice == "3":
            config['local_temp_path'] = input(f"本地临时路径 (当前: {config.get('local_temp_path', '未设置')}): ").strip()
        elif choice == "4":
            print("当前源项目路径:")
            for i, path in enumerate(config.get('source_project_paths', [])):
                print(f"{i+1}. {path}")
            
            action = input("选择操作 (add/remove/edit): ").strip().lower()
            if action == "add":
                new_path = input("输入新项目路径: ").strip()
                if new_path:
                    config['source_project_paths'].append(new_path)
            elif action == "remove":
                try:
                    idx = int(input("输入要删除的路径编号: ")) - 1
                    if 0 <= idx < len(config['source_project_paths']):
                        removed = config['source_project_paths'].pop(idx)
                        print(f"已删除: {removed}")
                except ValueError:
                    print("无效的编号")
            elif action == "edit":
                try:
                    idx = int(input("输入要编辑的路径编号: ")) - 1
                    if 0 <= idx < len(config['source_project_paths']):
                        new_path = input(f"新路径 (当前: {config['source_project_paths'][idx]}): ").strip()
                        if new_path:
                            config['source_project_paths'][idx] = new_path
                except ValueError:
                    print("无效的编号")
    
    if save_config(config):
        print("配置更新成功！")


def run_migration(config_file="config.json"):
    """运行迁移"""
    config = load_config(config_file)
    if not config:
        print("请先创建配置文件")
        return
        
    print("=== 开始迁移 ===")
    show_config(config)
    
    confirm = input("\n确认开始迁移? (y/N): ").strip().lower()
    if confirm != 'y':
        print("迁移已取消")
        return
        
    migrator = GitMigrator(config_file)
    migrator.config = config
    
    if migrator.migrate_all_projects():
        print("\n🎉 所有项目迁移成功！")
    else:
        print("\n❌ 部分项目迁移失败，请查看日志文件了解详情")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="Git仓库迁移工具")
    parser.add_argument("--config", "-c", default="config.json", help="配置文件路径")
    parser.add_argument("--create", action="store_true", help="创建新配置文件")
    parser.add_argument("--edit", action="store_true", help="编辑现有配置文件")
    parser.add_argument("--show", action="store_true", help="显示当前配置")
    parser.add_argument("--migrate", action="store_true", help="执行迁移")
    
    args = parser.parse_args()
    
    if args.create:
        config = create_config_interactive()
        if config:
            save_config(config, args.config)
        return
        
    if args.edit:
        edit_config()
        return
        
    if args.show:
        config = load_config(args.config)
        if config:
            show_config(config)
        return
        
    if args.migrate:
        run_migration(args.config)
        return
        
    # 如果没有指定参数，显示交互式菜单
    while True:
        print("\n=== Git仓库迁移工具 ===")
        print("1. 创建配置文件")
        print("2. 编辑配置文件")
        print("3. 查看配置")
        print("4. 执行迁移")
        print("0. 退出")
        
        choice = input("\n请选择 (0-4): ").strip()
        
        if choice == "0":
            print("再见！")
            break
        elif choice == "1":
            config = create_config_interactive()
            if config:
                save_config(config, args.config)
        elif choice == "2":
            edit_config()
        elif choice == "3":
            config = load_config(args.config)
            if config:
                show_config(config)
        elif choice == "4":
            run_migration(args.config)
        else:
            print("无效选择，请重新输入")


if __name__ == "__main__":
    main()

